# 用户反馈管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import UserFeedbackfeedback, Users, Recipes

# 用户反馈管理
def index(request, pIndex=1):
    """反馈列表页"""
    # 预加载关联数据，优化查询
    flist = UserFeedbackfeedback.objects.select_related('user', 'related_recipe').all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            flist = flist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        flist = flist.filter(
            Q(content__contains=kw) | 
            Q(user__username__contains=kw) |
            Q(reply__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 反馈类型筛选
    ftype = request.GET.get('ftype', '')
    if ftype:
        flist = flist.filter(feedback_type=ftype)
        mywhere.append(f'ftype={ftype}')
    
    # 解决状态筛选
    resolved = request.GET.get('resolved', '')
    if resolved in ['true', 'false']:
        flist = flist.filter(is_resolved=(resolved == 'true'))
        mywhere.append(f'resolved={resolved}')
    
    # 关联食谱筛选
    rid = request.GET.get('recipe', '')
    if rid:
        flist = flist.filter(related_recipe_id=rid)
        mywhere.append(f'recipe={rid}')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(flist, 10)  # 每页10条
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 获取相关数据用于筛选框
    feedback_types = dict(UserFeedbackfeedback.FEEDBACK_TYPE_CHOICES)
    recipes = Recipes.objects.all()
    
    context = {
        "feedbacklist": list2,
        'feedback_types': feedback_types,
        'recipes': recipes,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_ftype': ftype,
        'selected_resolved': resolved,
        'selected_recipe': rid
    }
    return render(request, "myadmin/userfeedback/index.html", context)

def add(request):
    """加载反馈添加表单（管理员手动添加用）"""
    users = Users.objects.all()
    recipes = Recipes.objects.all()
    feedback_types = UserFeedbackfeedback.FEEDBACK_TYPE_CHOICES
    context = {
        'users': users,
        'recipes': recipes,
        'feedback_types': feedback_types
    }
    return render(request, "myadmin/userfeedback/add.html", context)

def insert(request):
    """执行反馈添加"""
    try:
        ob = UserFeedbackfeedback()
        ob.user_id = request.POST.get('user_id')
        ob.feedback_type = request.POST.get('feedback_type')
        ob.content = request.POST.get('content')
        
        # 处理可选的关联食谱
        recipe_id = request.POST.get('related_recipe_id')
        ob.related_recipe_id = recipe_id if recipe_id else None
        
        # 管理员添加时可直接设置解决状态和回复
        ob.is_resolved = request.POST.get('is_resolved') == 'on'
        ob.reply = request.POST.get('reply', '')
        
        # 验证必填字段
        if not all([ob.user_id, ob.feedback_type, ob.content]):
            raise ValueError("用户、反馈类型和反馈内容为必填项")
        
        ob.save()
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': f"添加失败：{str(err)}"}
    return render(request, "myadmin/info.html", context)

def edit(request, fid=0):
    """加载反馈编辑表单（主要用于回复和更新解决状态）"""
    try:
        ob = UserFeedbackfeedback.objects.get(feedback_id=fid)
        recipes = Recipes.objects.all()
        feedback_types = UserFeedbackfeedback.FEEDBACK_TYPE_CHOICES
        context = {
            'feedback': ob,
            'recipes': recipes,
            'feedback_types': feedback_types
        }
        return render(request, "myadmin/userfeedback/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的反馈信息！"}
    return render(request, "myadmin/info.html", context)

def update(request, fid):
    """执行反馈编辑（主要处理回复和解决状态更新）"""
    try:
        ob = UserFeedbackfeedback.objects.get(feedback_id=fid)
        
        # 更新基本信息
        ob.feedback_type = request.POST.get('feedback_type')
        ob.content = request.POST.get('content')
        
        # 处理关联食谱
        recipe_id = request.POST.get('related_recipe_id')
        ob.related_recipe_id = recipe_id if recipe_id else None
        
        # 处理解决状态和回复
        ob.is_resolved = request.POST.get('is_resolved') == 'on'
        ob.reply = request.POST.get('reply', '').strip()
        
        # 验证必填字段
        if not all([ob.feedback_type, ob.content]):
            raise ValueError("反馈类型和反馈内容为必填项")
        
        ob.save()
        context = {'info': "更新成功！"}
    
    except UserFeedbackfeedback.DoesNotExist:
        context = {'info': "更新失败：反馈不存在！"}
    except ValueError as e:
        context = {'info': f"更新失败：{str(e)}"}
    except Exception as e:
        print(f"更新错误详情：{str(e)}")
        context = {'info': f"更新失败：{str(e)}"}
    
    return render(request, "myadmin/info.html", context)

def delete(request, fid=0):
    """执行反馈删除"""
    try:
        ob = UserFeedbackfeedback.objects.get(feedback_id=fid)
        ob.delete()
        context = {'info': "删除成功！"}
    except UserFeedbackfeedback.DoesNotExist:
        context = {'info': "删除失败：反馈不存在！"}
    except Exception as err:
        print(f"删除反馈时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)